import qs from 'qs'

var updown = {
    // 下载二进制文件
    saveBinaryFile: function (blob, { filename }) {

        if (window.URL && window.URL.createObjectURL) {
            var downloadEl = document.createElement('a')
            // var href = window.URL.createObjectURL(blob)  // 创建下载的链接
            debugger

            if (typeof (blob) == "string") {
                var binaryData = [];
                binaryData.push(blob);
                blob = new Blob(binaryData, { type: "application/excel" })
            }
            var href = window.URL.createObjectURL(blob)

            downloadEl.href = href
            downloadEl.setAttribute('target', '_blank')
            downloadEl.download = filename || ''   // 下载后文件名
            document.body.appendChild(downloadEl)
            downloadEl.click() // 点击下载
            document.body.removeChild(downloadEl) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
        }
    },

    /**
     * 下载后台文件
     * @param {*} response 后台返回的原始数据 包含header
     */
    downFile: function (response) {
        // 获取文件名
        var filename = qs.parse(response.headers['content-disposition'], {
            delimiter: ';',
        }).filename
        this.saveBinaryFile(response.data, { filename: filename })
    },

    /**
   *加载js文件
   *
   * @param {*} src文件路径
   * @returns Promise
   */
    loadAsyncScript: function (src) {
        return new Promise(function (resolve, reject) {
            var head = document.getElementsByTagName('head')[0]
            var script = document.createElement('script')
            script.setAttribute('type', 'text/javascript')
            script.setAttribute('src', src)
            script.setAttribute('async', true)
            script.setAttribute('defer', true)
            head.appendChild(script)

            // ie! duck type
            if (document.all) {
                script.onreadystatechange = function () {
                    var state = this.readyState
                    if (state === 'loaded' || state === 'complete') {
                        resolve()
                    } else {
                        reject(new Error())
                    }
                }
            } else {
                // firefox, chrome
                script.onload = function () { resolve() }
                script.onerror = function () { reject(new Error()) }
            }
        })
    },
    downloadRes: async (url, name) => {
        if (!name || name === '') {
            name = url.match(/^.+\/(\w+\.\w+)/i)
            
        }
        let response = await fetch(url)
        // 内容转变成blob地址
        let blob = await response.blob()
        // 创建隐藏的可下载链接
        let objectUrl = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        //地址
        a.href = objectUrl
        //修改文件名
        a.download = [name[1]]
        // 触发点击
        document.body.appendChild(a)
        a.click()
        //移除
        setTimeout(() => document.body.removeChild(a), 1000)
    }
}

export default updown